<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>

<%@ page import="com.storyroad.responseClasses.Story"%>

<%if(request.getSession().getAttribute("username")==null){
	response.sendRedirect(response
			.encodeRedirectURL(request.getContextPath()
					+ "/LoginPage.jsp"));
	}%>
	
	<% Story storyObject = (Story) request.getAttribute("storyObject"); %>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="description" content="">
  <meta name="author" content="">
  <link rel="shortcut icon" href="bootstrap/assets/ico/favicon.png">
  <script src="js/gen_validatorv4.js" type="text/javascript"></script>
  <link href="http://www.gstatic.com/freebase/suggest/4_1/suggest.min.css" rel="stylesheet" type="text/css">
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
  <script type="text/javascript" src="http://www.gstatic.com/freebase/suggest/4_1/suggest.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.12/jquery-ui.min.js" type="text/javascript" charset="utf-8"></script>
  <script src="tag-it-master/js/tag-it.js" type="text/javascript" charset="utf-8"></script>
  <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/flick/jquery-ui.css">
  <link href="tag-it-master/css/jquery.tagit.css" rel="stylesheet" type="text/css">
  <title>Create a New Story</title>

  <!-- Bootstrap core CSS -->
  <link href="bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">

  <!-- Custom styles for this template -->
  <link href="css/createstory.css" rel="stylesheet">
  
  <script>
	var mediaLink;
    function upload(file) {
      var fd = new FormData();
      fd.append("image", file);
      fd.append("key", "6528448c258cff474ca9701c5bab6927");
      var xhr = new XMLHttpRequest();
      xhr.open("POST", "http://api.imgur.com/2/upload.json", true);
      xhr.onload = function() {
        var link = JSON.parse(xhr.responseText).upload.links.original;        	 
        document.getElementById('mediaLink').value = link;       	 
        document.getElementById('imageShow').setAttribute("src", link);
	  };
	  xhr.send(fd);
    }
  </script>
  
  <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
  <script>
    var map;
    var marker;
    var browserSupportFlag =  new Boolean();
    /* Now sets the current locaiton as map center.
    * WE can modify it like if the current radio button is chosen,
    * Send the current location as form element, else use the marker.
    */
    function initialize() {
      var mapOptions = {
        zoom: 10,
        center: new google.maps.LatLng(11.100, 28.944),
        mapTypeId: google.maps.MapTypeId.ROADMAP
      };
      map = new google.maps.Map(document.getElementById('map-canvas'),
        mapOptions);
      
      google.maps.event.addListener(map, 'click', function(event) {
        placeMarker(event.latLng);
      });
      
      lat = ( <%= String.valueOf(storyObject.getX_coord()) %> );
      long = ( <%= String.valueOf(storyObject.getY_coord()) %> );
      centerPoint = new google.maps.LatLng(lat, long);
      map.setCenter(centerPoint);
      placeMarker(centerPoint);
      
      if(navigator.geolocation) {
        browserSupportFlag = true;
        navigator.geolocation.getCurrentPosition(function(position) {
          initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
          
        }, function() {
          handleNoGeolocation(browserSupportFlag);
        });
      }
        // Browser doesn't support Geolocation
        else {
          browserSupportFlag = false;
          handleNoGeolocation(browserSupportFlag);
        }

        function handleNoGeolocation(errorFlag) {
          if (errorFlag == true) {
            alert("Geolocation service failed.");
            initialLocation = newyork;
          } else {
            alert("Your browser doesn't support geolocation. We've placed you in Siberia.");
            initialLocation = siberia;
          }
        }
      }

      function placeMarker(location) {
        if ( marker ) {
          marker.setPosition(location);
        } else {
          marker = new google.maps.Marker({
            position: location,
            map: map
          });
        }
        document.getElementById("id_lat").value = marker.getPosition().toUrlValue();
      }

      google.maps.event.addDomListener(window, 'load', initialize);
    </script>
    
    <script type="text/javascript">
    $(document).ready(function() {
    	
    	var title =  new String("<%= String.valueOf(storyObject.getTitle()) %>") ;
    	var storyLocation = new String("<%= String.valueOf(storyObject.getLocation()) %>") ;
    	var storyId = new String("<%= String.valueOf(storyObject.getS_id()) %>") ;
    	
    	document.getElementById('titleInput').value = title;
    	document.getElementById('locationInput').value = storyLocation;
    	document.getElementById('s_id').value = storyId;
    });
    
    </script>

    
    <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
      <script src="../../assets/js/html5shiv.js"></script>
      <script src="../../assets/js/respond.min.js"></script>
      <![endif]-->
    </head>

    <body background="img/back_nologo.png">
      <div class="navbar navbar-fixed-top navbar-inverse" role="navigation">
        <div class="container">
          <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
              <span class="icon-bar"></span>
              <span class="icon-bar"></span>
              <span class="icon-bar"></span>
            </button>
            <img src="img/logo_writing.png" id="top_logo">
          </div>
          <div class="collapse navbar-collapse">
            <ul class="nav navbar-nav">
              <li><a href="MainPage">Home Page</a></li>
              <li><a href="GetRecommendations">Recommendations</a></li>
              <li><a href="Search.jsp">Search Stories</a></li>
              <li><a href="GetFollowers">Following</a></li>
            </ul>
            <ul class="nav navbar-nav" id="profile_buttons">
              <li><a href="GetProfile">My Profile</a></li>
              <li><a href="Logout">Logout</a></li>
            </ul>
          </div><!-- /.nav-collapse -->

        </div><!-- /.container -->
      </div><!-- /.navbar -->

      <div class="container">
        <div class="jumbotron" id="create-story-container">
          <center><h1>Edit Your Story</h1></center>
          <form action="UpdateStory" method="POST" id="createstory">
            <div class="row">
              <div class="col-lg-6">

                <label for="titleInput">Title:</label>
                <input type="text" name="title" class="form-control" id="titleInput" placeholder="Write a title...">
                <label for="storyInput">Story:</label>
                <p><textarea class="form-control" id="bodyInput" name="body" rows="29" placeholder="Write the story..."><%out.print(storyObject.getBody()); %></textarea></p>

                <p style="float:right"><a><img id="imageShow" alt="" src="holder.js/300x200/text: " /></a><input type="file" onchange="upload(this.files[0])" title="Search for a file to add"></p>


              </div>
              <div class="col-lg-6">
                <div class="form-inline">
                  <label class="radio-inline" style="font-size:12pt">
                    <input type="radio" name="locationOption" id="useCurrent" value="useCurrent" checked>Use my current location
                  </label>
                  <label class="radio-inline" style="font-size:12pt">
                    <input type="radio" name="locationOption" id="selectFromMap" value="selectFromMap">Select from map
                  </label>
                </div>
                <div id="map-canvas"></div>
                <input type="text" name="coordinates" id="id_lat" style="display:none"/>
                <input type="text" class="form-control" id="locationInput" name="location" placeholder="Write a short location description">
                <input type="hidden" name="request_type" value="Web">
                <input type="hidden" name="story_id" id="s_id" value="">
                <input type="hidden" id="mediaLink" name="media_link" value="Web">          
                <p style="float:right" id="button-container">
                  <button class="btn btn-success" id="create-button" type="submit">Update</button>
                  <button class="btn btn-danger" href="#" id="create-button">Discard</button>
                </p>
              </form>
              <script  type="text/javascript">
               var frmvalidator = new Validator("createstory");
               frmvalidator.addValidation("title","req","Please enter a title for your story.");
               frmvalidator.addValidation("body","req","Please enter a body for your story.");
               frmvalidator.addValidation("location","req","Please enter a location for your story.");
               frmvalidator.addValidation("body","maxlen=1024","Your story cannot be longer than 1024 characters.");
             </script>
           </div>
         </div><!--/.container-->



    <!-- Bootstrap core JavaScript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->

    <script src="bootstrap/dist/js/bootstrap.min.js"></script>
    <script src="js/holder.js"></script>
    <script src="js/bootstrap.file-input.js"></script>
    <script>$(document).ready(function(){$('input[type=file]').bootstrapFileInput();});</script>
    
  </body>
  </html>
